<?php

namespace App\Console\Commands;

use App\Models\Account;
use App\Models\GiveURewad;
use App\Models\ReleaseLeader;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class Leader extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'leader';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '团队收益';

    /**
     * Create a new command instance.
     */
    public function __construct()
    {
        parent::__construct();
    }


    public function handle()
    {
        logger('==团队收益结算==');
        $users = User::where('vip_level', '>', 0)->get();
        foreach ($users as $user) {
            $this->leader($user);
        }
    }

    /**
     * 团队收益.
     */
    protected function leader($user)
    {
        logger($user);
        $rate = Setting::whereIn('key', ['level_1', 'level_2', 'level_3', 'level_4', 'level_5', 'level_6'])
            ->orderBy('id', 'asc')
            ->pluck('value');
        $condition = Setting::whereIn('key', ['level1_value', 'level2_value', 'level3_value', 'level4_value', 'level5_value', 'level6_value'])
            ->orderBy('id', 'asc')
            ->pluck('value');

        $user_ids = User::where('_lft', '>', $user->_lft)
            ->where('_rgt', '<', $user->_rgt)
            ->pluck('id');

        // 统计当天日收益
        $start = Carbon::now()->startOfDay()->subDay();
        $end = Carbon::now()->endOfDay()->subDay();
        $reward = GiveURewad::whereIn('user_id', $user_ids)->where('status', 1)->whereBetween('created_at', [$start, $end])->sum('reward');
        logger("团队日收益：{$reward}");

        if ($reward < $condition[0]) {
            logger("不满足条件，没有团队收益");
            return;
        } elseif ($reward >= $condition[0] && $reward < $condition[1]) {
            $should_rate = $rate[0];
        } elseif ($reward >= $condition[1] && $reward < $condition[2]) {
            $should_rate = $rate[1];
        } elseif ($reward >= $condition[2] && $reward < $condition[3]) {
            $should_rate = $rate[2];
        } elseif ($reward >= $condition[3] && $reward < $condition[4]) {
            $should_rate = $rate[3];
        } elseif ($reward >= $condition[4] && $reward < $condition[5]) {
            $should_rate = $rate[4];
        } elseif ($reward >= $condition[5]) {
            $should_rate = $rate[5];
        }

        // 计算领导奖
        $leader_reward = bcmul($reward, $should_rate);
        logger("拿你伞下所有人日收益的百分比例：{$should_rate}，奖励数量：{$leader_reward}");

        // 用户账户
        /** @var Account $account */
        $account = Account::firstOrCreate([
            'user_id' => $user->id,
            'coin_id' => 1,
        ])->refresh();

        // 已结算过
        $leader = ReleaseLeader::where('user_id', $user->id)
            ->whereDate('time', today())
            ->exists();
        if ($leader) {
            logger("今天已经结算过，不能重复结算");
            return;
        }

        // 团队收益明细
        $leader = new ReleaseLeader();
        $leader->user_id = $user->id;
        $leader->child_user_id = 0;
        $leader->order_id = 0;
        $leader->total = $reward;
        $leader->rate = $should_rate;
        $leader->profit = $leader_reward;
        $leader->time = now();
        if ($leader->profit <= 0) {
            return;
        }

        DB::transaction(function () use ($leader, $account) {
            $leader->save();

            // 更新账户
            /** @var Account $account */
            $account = Account::lockForUpdate()->find($account->id);
            $account->availableIncrement($leader->profit);
            $account->type = '团队收益';
            $account->action_id = $leader->id;
            $account->save();
        });
    }
}
